package hot_information.rss;

import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONObject;

public class Rss_servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		PrintWriter out = response.getWriter();   //获取输出对象
		
		FileInputStream in = new FileInputStream(request.getSession().getServletContext().getRealPath("/WEB-INF/classes/hot_information/rss/news.xml"));
		InputStreamReader c_in = new InputStreamReader(in,"UTF-8");    //转换为字符流
		
		SAXReader reader = new SAXReader();     //saxreader创建SAX解析事件dom4j树
		try {
			Document   document = reader.read(c_in);
			
			Element root = document.getRootElement();   //获取根元素
			Element channel = root.element("channel");       //这个需要一级一级的选elements只表示下一级子元素
			@SuppressWarnings("unchecked")
			List<Element> childList = channel.elements("item");    //获取每一个新闻元素
			
			//ArrayList<JSONObject> json_list  = new ArrayList<JSONObject>();    //返回json数组
			
			
			JSONArray jsonArray = new JSONArray();
			JSONObject jsonObj;
            
			
			 for(ListIterator<Element> it = childList.listIterator();it.hasNext();){    //循环遍历获取新闻内容
		        	
		        	Element element = (Element) it.next();
		        	Element title = element.element("title");
		        	Element link = element.element("link");
		        	Element description = element.element("description");
		       	
		        	
		        	jsonObj = new JSONObject();
		            jsonObj.put("title", title.getText());
		            jsonObj.put("link", link.getText());
		            jsonObj.put("description", description.getText());
		            jsonArray.put(jsonObj);
		            
		        	//System.out.println(title.getText()+"       "+link.getText()+"   "+description.getText());
			 }
			
			 //System.out.println(jsonArray.toString());
			 out.print(jsonArray.toString());     //返回json数据
			 
		} catch (Exception e) {
			out.print(false);     //读取json文件失败的话，返回false
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}

}
